//
//  SISSHomeHousingViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/23.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSHomeHousingViewController.h"
#import "SISSHousingCell.h"
#import "SISSNetworkingManager+Home.h"
#import "SISSHouseResourceDetailVC.h"
#import "SISSRecommendPassengerViewController.h"
#import "SISSFindHouseResourcesViewController.h"

#import "SISSJsonRequestNetworkingManager+Registration.h"

static NSString * const HousingCellID = @"HousingCellID";

@interface SISSHomeHousingViewController ()<UITableViewDataSource,UITableViewDelegate,SISSHousingCellDelegate>

/** 房源数组 */
@property (strong, nonatomic) NSArray<SISSHouseResourceModel *> *houseResourceArr;


@end

@implementation SISSHomeHousingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestNewestHouseResourceData];
    
    // 去掉系统自带底部的线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 自动行高
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"SISSHousingCell" bundle:nil] forCellReuseIdentifier:HousingCellID];
}

- (void)setCanScroll:(BOOL)canScroll {
    _canScroll = canScroll;
    self.tableView.scrollEnabled = canScroll;
}


#pragma mark - UITableViewDataSource
// 返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    [tableView tableViewDisplayWithMessage:@"没有找到相关房源！" ifNecessaryForRowCount:self.houseResourceArr.count];
    if (self.houseResourceArr.count > 0) {
        return self.houseResourceArr.count + 1;
    }
    return self.houseResourceArr.count;
}


// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSHousingCell *cell = [tableView dequeueReusableCellWithIdentifier:HousingCellID forIndexPath:indexPath];
    
    cell.delegate = self;
    
    if (indexPath.row == self.houseResourceArr.count) {
        static NSString * const reuseID = @"ID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseID];
            UIButton *view = [[UIButton alloc] initWithFrame:cell.contentView.bounds];
            [cell.contentView addSubview:view];
            
            UIButton *button = [[UIButton alloc] init];
            [button setTitle:@"查看更多房源" forState:UIControlStateNormal];
            [button setTitleColor:COLOR(0x8998A5) forState:UIControlStateNormal];
            button.titleLabel.font = [UIFont systemFontOfSize:13];
            [button addTarget:self action:@selector(jumpToHouseResourceList) forControlEvents:UIControlEventTouchUpInside];
            [view addSubview:button];
            
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(cell.contentView);
            }];
        }
        return cell;
    }
    cell.houseResourceModel = self.houseResourceArr[indexPath.row];
    
    return cell;
}

- (void)jumpToHouseResourceList {
    
    SISSFindHouseResourcesViewController *vc = [[SISSFindHouseResourcesViewController alloc] init];
    vc.view.backgroundColor = [UIColor whiteColor];
    vc.title = @"找房源";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 去除tableView的选中状态
    SISSHouseResourceDetailVC *vc = [[SISSHouseResourceDetailVC alloc] init];
    vc.title = @"房源详情";
    SISSHouseResourceModel *houseModel = self.houseResourceArr[indexPath.row];
    vc.houseResourceModel = houseModel;
    if (houseModel.read != 1) {
        
        [kNetworkManager setHouseResourceReadWithHouseId:houseModel.ID success:^(id responseObject) {
            
            if ([responseObject[@"code"] integerValue] == 200) {
                NSLog(@"插入成功！");
            }
            
        } failed:^(NSError *error) {
            
            NSLog(@"%@",error);
        }];
    }
    self.houseResourceArr[indexPath.row].read = 1;
    [self.tableView reloadData];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0 && self.isForbiddenBlock) {
        self.isForbiddenBlock(NO);
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.row == 0 && self.isForbiddenBlock) {
        self.isForbiddenBlock(YES);
    }
}

#pragma mark - SISSHousingCellDelegate
- (void)housingCellRecommendButtonDidClick:(UIButton *)button {
    
    SISSHousingCell *cell = (SISSHousingCell *)button.nextResponder.nextResponder;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    SISSHouseResourceModel *model = self.houseResourceArr[indexPath.row];
    
    SISSRecommendPassengerViewController *vc = [[SISSRecommendPassengerViewController alloc] init];
    vc.title = @"推荐客源";
    vc.ahrId = model.ID;
    vc.recommendSuccessBlock = ^{
        [self requestNewestHouseResourceData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
//    if ([self.delegate respondsToSelector:@selector(homeHousingViewDidScroll:)]) {
//        
//        [self.delegate homeHousingViewDidScroll:scrollView.contentOffset.y];
//    }
}

#pragma mark - 2.1.1 首页20条最新房源客源
- (void)requestNewestHouseResourceData {

    WeakSelf
    [SISSPublicSingleton shared].isHud = YES;
    [kNetworkManager requestNewestHouseResourceWithSuccess:^(NSArray<SISSHouseResourceModel *> *houseResources) {
        
        weakSelf.houseResourceArr = [NSArray arrayWithArray:houseResources];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [weakSelf.tableView reloadData];
            
             [weakSelf endHeaderRefresh];
        }];
 
    } failed:^(NSError *error) {
        [weakSelf endHeaderRefresh];
        NSLog(@"%@",error);
    }];
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownReloadMoreData {
    
    [self requestNewestHouseResourceData];
}


- (void)reloadMoreData {
    WeakSelf
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf endfooterRefresh];
    });
}

@end
